数学模型

Wang Haihua

🍈 🍉🍊 🍋 🍌


可以使用Python的Sympy库求微分方程的符号解,Scipy库求微分方程的数值解;本文介绍符号解。

符号解

例1

求下述微分方程的特解 $$ \left\{\begin{array}{l} \frac{d^{2} y}{d x^{2}}+4 \frac{d y}{d x}+2 y=0 \\ y(0)=0, \quad y^{\prime}(0)=1 \end{array}\right. $$

Python代码

from sympy.abc import x
from sympy import diff, dsolve, simplify, Function

y=Function('y')
eq=diff(y(x),x,2)+2*diff(y(x),x)+2*y(x)  #定义方程

con={y(0): 0, diff(y(x),x).subs(x,0): 1}  #定义初值条件
y=dsolve(eq, ics=con)
print(simplify(y))

求解得到: $$y(x)=e^{-x}\sin x$$

例2

求下述微分方程的解: $$ \left\{\begin{array}{l} \frac{d^{2} y}{d x^{2}}+2 \frac{d y}{d x}+2 y=\sin x \\ y(0)=0, \quad y^{\prime}(0)=1 \end{array}\right. $$

from sympy.abc import x  #引进符号变量x
from sympy import Function, diff, dsolve, sin
y=Function('y')
eq=diff(y(x),x,2)+2*diff(y(x),x)+2*y(x)-sin(x)  #定义方程
con={y(0): 0, diff(y(x), x).subs(x,0): 1}  #定义初值条件
y=dsolve(eq, ics=con)
print(y)

解为 $$ y{\left(x \right)} = \frac{\left(\left(\sin{\left(x \right)} - 2 \cos{\left(x \right)}\right) e^{x} + 6 \sin{\left(x \right)} + 2 \cos{\left(x \right)}\right) e^{- x}}{5} $$

例3

求下列微分方程组的解: $$ \begin{cases}\frac{d x_{1}}{d t}=2 x_{1}-3 x_{2}+3 x_{3}, & x_{1}(0)=1 \\ \frac{d x_{2}}{d t}=4 x_{1}-5 x_{2}+3 x_{3}, & x_{2}(0)=2 \\ \frac{d x_{3}}{d t}=4 x_{1}-4 x_{2}+2 x_{3}, & x_{3}(0)=3\end{cases} $$

import sympy as sp
t=sp.symbols('t')
x1,x2,x3=sp.symbols('x1,x2,x3',cls=sp.Function)
eq=[x1(t).diff(t)-2*x1(t)+3*x2(t)-3*x3(t),
    x2(t).diff(t)-4*x1(t)+5*x2(t)-3*x3(t),
    x3(t).diff(t)-4*x1(t)+4*x2(t)-2*x3(t)]
con={x1(0):1, x2(0):2, x3(0):3}
s=sp.dsolve(eq, ics=con); print(s)

结果为 $$ \left[ \operatorname{x_{1}}{\left(t \right)} = 2 e^{2 t} - e^{- t}, \ \operatorname{x_{2}}{\left(t \right)} = 2 e^{2 t} - e^{- t} + e^{- 2 t}, \ \operatorname{x_{3}}{\left(t \right)} = 2 e^{2 t} + e^{- 2 t}\right] $$

另一种写法

import sympy as sp
t=sp.symbols('t')
x1,x2,x3=sp.symbols('x1:4',cls=sp.Function)
x=sp.Matrix([x1(t),x2(t),x3(t)])
A=sp.Matrix([[2,-3,3],[4,-5,3],[4,-4,2]])
eq=x.diff(t)-A*x
s=sp.dsolve(eq,ics={x1(0):1,x2(0):2,x3(0):3})
print(s)

结果为 $$ \left[ \operatorname{x_{1}}{\left(t \right)} = 2 e^{2 t} - e^{- t}, \ \operatorname{x_{2}}{\left(t \right)} = 2 e^{2 t} - e^{- t} + e^{- 2 t}, \ \operatorname{x_{3}}{\left(t \right)} = 2 e^{2 t} + e^{- 2 t}\right] $$